package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveSetmeal(SetmealDto setmealDto) {
        List<SetmealDish> list=setmealDto.getSetmealDishes();
        Setmeal setmeal=new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        log.info("aaaaaaaa:"+setmeal);
        log.info(list.toString());
        this.save(setmeal);
        List<SetmealDish> list1=new ArrayList<>();
        for (SetmealDish s:
             list) {
            s.setSetmealId(setmeal.getId());
            list1.add(s);
        }
        setmealDishService.saveBatch(list1);

    }

    @Override
    public SetmealDto selectById(Long id) {
        SetmealDto setmealDto=new SetmealDto();
        //查询套餐
        Setmeal byId = this.getById(id);

        //查询菜品明细
        LambdaQueryWrapper<SetmealDish> qw=new LambdaQueryWrapper();
        qw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(qw);

        //拷贝
        BeanUtils.copyProperties(byId,setmealDto);
        setmealDto.setSetmealDishes(list);

        return setmealDto;
    }

    @Override
    public void modifySetmeal(SetmealDto setmealDto) {
        Setmeal setmeal=new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        //修改套餐数据
        this.updateById(setmeal);

        //清除原有的套餐的菜品数据
        LambdaQueryWrapper<SetmealDish> qw=new LambdaQueryWrapper();
        qw.eq(SetmealDish::getSetmealId,setmeal.getId());
        setmealDishService.remove(qw);

        //获取新的菜品数据
        List<SetmealDish> list=setmealDto.getSetmealDishes();
        List<SetmealDish> list1=new ArrayList<>();
        for (SetmealDish s:
             list) {
            s.setSetmealId(setmeal.getId());
            list1.add(s);
        }
        //存储数据
        setmealDishService.saveBatch(list1);
    }
}
